//
//  ChangePatientViewControllerDelegate.m
//  StraightTrain
//
//  Created by mk on 15/11/30.
//  Copyright © 2015年 mk. All rights reserved.
//

#import "ChangePatientViewController.h"

@interface ChangePatientViewController ()
{
    BOOL showCityPick;//显示城市
    UITextField * textNow;//当前响应的text

    int keyHeight;
    
}

@end

@implementation ChangePatientViewController

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self clearView];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
}

#pragma mark 创建城市pick
-(void)createCityPicker
{
    if (!pickCity)
    {
        pickCity = [[CityPickView alloc] init];
        pickCity.selectDelegate = self;
        pickCity.backgroundColor = [UIColor whiteColor];
        [pickCity setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.view addSubview:pickCity];
        NSDictionary *views = NSDictionaryOfVariableBindings(pickCity);
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0@1000-[pickCity]-0@1000-|"
                                                                          options:0
                                                                          metrics:nil
                                                                            views:views]];
        
        NSLayoutConstraint *constraintHE = [NSLayoutConstraint constraintWithItem:self.view
                                                                        attribute:NSLayoutAttributeBottom
                                                                        relatedBy:NSLayoutRelationEqual
                                                                           toItem:pickCity
                                                                        attribute:NSLayoutAttributeBottom
                                                                       multiplier:1
                                                                         constant:-202];
        [self.view addConstraint:constraintHE];
        
        NSLayoutConstraint *constraintV = [NSLayoutConstraint constraintWithItem:pickCity
                                                                       attribute:NSLayoutAttributeHeight
                                                                       relatedBy:NSLayoutRelationEqual
                                                                          toItem:nil
                                                                       attribute:NSLayoutAttributeHeight
                                                                      multiplier:1
                                                                        constant:202];
        [self.view addConstraint:constraintV];
    }
    
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [scrollMain setAlwaysBounceVertical:YES];
    
    titleLabel.text = @"修改患者资料";
    
    [self createCityPicker];
    
    for(UIImageView * imageBG in [viewMain subviews])
    {
        if (imageBG.tag>=100)
        {
            [imageBG setImage:[[UIImage imageNamed:@"default_text_wither_bg.png"] stretchableImageWithLeftCapWidth:20 topCapHeight:20]];
        }
    }
    
    //datePick
    [pickTime setMaximumDate:[NSDate new]];
    [pickTime setBackgroundColor:[UIColor whiteColor]];
    [pickTime setDate:[NSDate date] animated:NO];
    [pickTime setDatePickerMode:UIDatePickerModeDate];
    labTimeTitle.text = [CommonFunctions convertDate:[NSDate date] withFormatter:@"yyyy-MM" subFromIndex:0];
    
    [self loagUserData];
}

-(void)loagUserData
{
    //描述
    textName.text = self.userInfo.patien_name;
    textTel.text = self.userInfo.patien_mobile;
    textDiseaseName.text = self.userInfo.patien_diseaseName;//疾病名称
    tevDiseaseDescription.text = self.userInfo.patien_diseaseDetail;//疾病描述
    labTime.text = [NSString stringWithFormat:@"%@-%@",self.userInfo.patien_birthYear,self.userInfo.patien_birthMonth];
    
    if ([self.userInfo.patien_cityName isEqualToString:self.userInfo.patien_stateName])
    {
        labCity.text = [NSString stringWithFormat:@"%@市",self.userInfo.patien_cityName];
    }else
    {
        labCity.text = [NSString stringWithFormat:@"%@省/%@市",self.userInfo.patien_stateName,self.userInfo.patien_cityName];
    }
    
     pickCity.cityTitle.text = labCity.text;

}

#pragma mark 选择时间
-(IBAction)selectTime:(id)sender
{
    [textNow resignFirstResponder];
    [tevDiseaseDescription resignFirstResponder];
    [self showCityPickerData:NO];
    [self showdatePick:YES];
    
}

#pragma mark 确定选择时间
-(IBAction)selectTimeOK:(id)sender
{
    labTime.text = labTimeTitle.text;
    [self showdatePick:NO];
}

#pragma mark 取消选择时间
-(IBAction)selectTimeNO:(id)sender
{
    [self showdatePick:NO];
}

-(IBAction)timeValueChange
{
    labTimeTitle.text = [CommonFunctions convertDate:pickTime.date withFormatter:@"yyyy-MM" subFromIndex:0];
}

#pragma mark 选择城市
-(IBAction)selectCity:(id)sender
{
    [textNow resignFirstResponder];
    [tevDiseaseDescription resignFirstResponder];
    [self showCityPickerData:YES];
    [self showdatePick:NO];
}

#pragma marl cityPickView

-(void)citytoolBarDoneClick:(id)sender
{
    labCity.text = pickCity.cityTitle.text;
}


-(IBAction)btnNext:(id)sender
{
    
    [self clearView];
    
    NSString * strTel = TextNsString(textTel.text)
    NSString * strName = TextNsString(textName.text)
    NSString * strDiseaseName = TextNsString(textDiseaseName.text)
    NSString * strDiseaseDescription = TextNsString(tevDiseaseDescription.text)
    if(strTel.length>0 && strName.length>0 && strDiseaseName.length>0 && strDiseaseDescription.length>0)
    {
        NSMutableDictionary * dicData = [[NSMutableDictionary alloc]initWithCapacity:0];
        
        [dicData setObject:[gProjConfig.dicUserData objectForKey:USER_tel] forKey:@"username"];
        [dicData setObject:[gProjConfig.dicUserData objectForKey:USER_token] forKey:@"token"];
        [dicData setObject:strTel forKey:@"mobile"];
        [dicData setObject:strName forKey:@"name"];
        [dicData setObject:strDiseaseName forKey:@"disease_name"];
        [dicData setObject:strDiseaseDescription forKey:@"disease_detail"];
        
        //省
        NSMutableDictionary * dicProvince = [gProjConfig.arrCity objectAtIndex:pickCity.selectProvince];
        NSString * strProvinceID = [dicProvince objectForKey:@"id"];
        //市
        NSMutableArray * arrayCity = [dicProvince objectForKey:@"subCity"];
        NSMutableDictionary * dicCity = [arrayCity objectAtIndex:pickCity.selectCity];
        NSString * strCityID = [dicCity objectForKey:@"id"];
        
        [dicData setObject:strProvinceID forKey:@"state_id"];//省
        [dicData setObject:strCityID forKey:@"city_id"];//市
       
        [dicData setObject:labTime.text forKey:@"birth"];

        NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:dicData,@"patient", nil];
        SetHUDStartText(@"修改信息..")
        
        NSString * strUrl = [NSString stringWithFormat:@"%@/%@",[gProjConfig.dicAllUrl objectForKey:@"createPatientUrl"],self.userInfo.patien_id];
        [[HttpClient manager]PUT:strUrl
                            parameters:dic
            success:^(AFHTTPRequestOperation *operation, id responseObject)
             {
                 SetHUDHidden;
                 SetHUDFinishedText(@"资料修改成功")
               //  DLog(@"==%@",responseObject);
             }
            failure:^(AFHTTPRequestOperation *operation, NSError *error)
             {
                 SetHUDHidden;
                 HUDShowRequestError(error.domain, self.view)
             }];
        
    }else
    {
        Alert(alerTitle, @"请填写完整资料信息", @"确定")
    }
    
}

-(void)hudWasHidden:(MBProgressHUD *)hud
{
    //修改成功
    if ([self.delegate respondsToSelector:@selector(changePatientDataSuccess)])
    {
        [self.delegate changePatientDataSuccess];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma marl cityPickView
-(void)selectPickData:(NSString *)city provinceData:(NSString *)province
{
    if ([city isEqualToString:province])
    {
        labCity.text = [NSString stringWithFormat:@"%@市",city];
    }else
    {
        labCity.text = [NSString stringWithFormat:@"%@省/%@市",province,city];
    }
    
}


-(void)showdatePick:(BOOL)showDate
{
  
    for (NSLayoutConstraint * constraints in [viewAllPick.superview constraints])
    {
        if (constraints.firstItem == viewAllPick.superview && constraints.firstAttribute == NSLayoutAttributeBottom && constraints.secondItem == viewAllPick && constraints.secondAttribute == NSLayoutAttributeBottom)
        {
            [UIView animateWithDuration:0.2 animations:^
             {
                 constraints.constant = (showDate?0:-202);
                 [self.view layoutIfNeeded];
             }];
            break;
        }
    }
    
}

#pragma mark showDataView
-(void)showCityPickerData:(BOOL)show
{
    for (NSLayoutConstraint *constraints in [pickCity.superview constraints])
    {
        if (constraints.firstItem == self.view && constraints.secondItem == pickCity && constraints.firstAttribute == NSLayoutAttributeBottom && constraints.secondAttribute == NSLayoutAttributeBottom)
        {
            [UIView animateWithDuration:0.2 animations:^
             {
                 constraints.constant = (show?0:-202);
                 [self.view layoutIfNeeded];
             } completion:^(BOOL finished)
             {
             }];
            break;
        }
    }
    
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark textFieldDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self showdatePick:NO];
    [self showCityPickerData:NO];
    textNow = textField;
    [self changeViewFrame];
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [scrollMain setContentOffset:CGPointMake(0,0) animated:YES];
}

-(void)textViewDidBeginEditing:(UITextView *)textView
{
    [self showdatePick:NO];
    [self showCityPickerData:NO];
    textNow = nil;
    [self changeViewFrame];
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
    {
        [textView resignFirstResponder];
        [scrollMain setContentOffset:CGPointMake(0,0) animated:YES];
        return NO;
    }
    return YES;
}

#pragma mark //当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyHeight = keyboardRect.size.height;
    
    [self changeViewFrame];
}

-(void)changeViewFrame
{
    int bottomDistance;
    if (textNow == nil)
    {
        bottomDistance = appScreenHeight -  tevDiseaseDescription.bottom-64;//键盘预留高度
    }else
    {
        bottomDistance = appScreenHeight - textNow.bottom-64;//键盘预留高度
    }
    
    int content = bottomDistance - (keyHeight + 30);//键盘到text得间距
    
    if (content < 0)
    {
        [scrollMain setContentOffset:CGPointMake(0,-content) animated:YES];
    }
}


-(void)textfieldContentWithoutAnimate:(NSLayoutConstraint *)constraint
{
    [UIView animateWithDuration:0.2 animations:^{
        
        [scrollMain setContentOffset:CGPointMake(0,0) animated:NO];
        
    }];
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [textNow resignFirstResponder];
    [tevDiseaseDescription resignFirstResponder];
}

-(IBAction)clearView
{
    [tevDiseaseDescription resignFirstResponder];
    [textNow resignFirstResponder];
    [self showCityPickerData:NO];
    [self showdatePick:NO];
    [scrollMain setContentOffset:CGPointMake(0,0) animated:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end




